﻿
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;

namespace BBPA.Admin
{
    public static class Security
    {
        public static int thisUserID = 0;
        /// <summary>
        /// 判断是否登录成功
        /// </summary>
        /// <param name="loginusername">登陆用户名</param>
        /// <param name="loginpassword">登陆密码</param>
        /// <param name="loginusertype">登录类型</param>
        /// <returns>是否登录成功</returns>
        public static CallBak<int> CHKlogin(string loginusername, string loginpassword)
        {
            CallBak<int> callBak = new CallBak<int>();
            //Logout();
            if (loginusername == "" || loginpassword == "")
                return callBak.Err("用户名和密码必须填写");
            else
            {
                loginusername = loginusername.ToLower();

                CallBak<int> getLoginUserID = GetUserID_by_LoginForm(loginusername, StringPlus.md5(loginpassword));
                if (!getLoginUserID.IsSuccess) return getLoginUserID;

                int UserID = getLoginUserID.ReturnVal;
                
                if (HttpContext.Current.Request.Cookies["UserID"] != null) HttpContext.Current.Response.Cookies["UserID"].Value = UserID.ToString();
                else
                {
                    HttpCookie cookie_UserID = new HttpCookie("UserID");
                    //cookie_UserName.Value = HttpUtility.UrlEncode(loginusername);
                    cookie_UserID.Value = UserID.ToString();
                    HttpContext.Current.Response.Cookies.Add(cookie_UserID);
                }

                if (HttpContext.Current.Request.Cookies["Password"] != null) HttpContext.Current.Response.Cookies["Password"].Value = StringPlus.md5(loginpassword);
                else
                {
                    HttpCookie cookie_PassWord = new HttpCookie("Password");
                    cookie_PassWord.Value = StringPlus.md5(loginpassword);
                    HttpContext.Current.Response.Cookies.Add(cookie_PassWord);
                }
                return getLoginUserID;
            }
        }
        /// <summary>  
        /// 清除CookieValue  
        /// </summary>  
        /// <param name="CookieName">Cookie名称</param>  
        public static void ClearCookie(string cookieName__)
        {

         
            string cookieName;
            int limit = System.Web.HttpContext.Current.Request.Cookies.Count;
            for (int i = 0; i < limit; i++)
            {
                cookieName = System.Web.HttpContext.Current.Request.Cookies[i].Name;
                if (System.Web.HttpContext.Current.Request.Cookies[cookieName] != null && DataTypePlus.requestString(System.Web.HttpContext.Current.Request.Cookies[cookieName]) == cookieName__)
                {
                    HttpCookie aCookie = new HttpCookie(cookieName);
                    System.Web.HttpContext.Current.Response.Cookies.Remove(cookieName);//清除
                    aCookie.Expires = DateTime.Now.AddYears(-1);
                    System.Web.HttpContext.Current.Response.Cookies.Add(aCookie);
                    System.Web.HttpContext.Current.Response.Cookies[cookieName].Expires = DateTime.Now.AddYears(-1);   
                }
            }


        }


        /// <summary>
        /// 用户注销
        /// </summary>
        /// <returns>是否注销成功</returns>
        public static bool Logout()
        {
            HttpCookieCollection cookies = HttpContext.Current.Request.Cookies;
            for (int i = 0; i < cookies.Count; i++)
            {
                string cookiename = cookies[i].Name;
                if (HttpContext.Current.Request.Cookies[cookiename] != null)
                {
                    HttpCookie myCookie = new HttpCookie(cookiename);
                    System.Web.HttpContext.Current.Response.Cookies.Remove(cookiename);//清除
                    myCookie.Expires = DateTime.Now.AddDays(-1d);
                    HttpContext.Current.Response.Cookies.Add(myCookie);
                }
            }
            return true;
        }



        /// <summary>
        /// 验证用户登陆状态和操作权限
        /// </summary>
        /// <param name="rightID"></param>
        public static void CheckUserRight()
        {
            if (IsLogined())
            {

            }
            else
            {
                Logout();
                JsHelper.Alert("请先登录再操作");
                JsHelper.RefreshParent();
                System.Web.HttpContext.Current.Response.End();
            }
        }




        /// <summary>
        /// 判断是否已登陆

        /// </summary>
        /// <returns></returns>
        public static bool IsLogined()
        {
            int UserID = 0;
            string Password = "";

            //if (HttpContext.Current.Request.Cookies["UserID"] != null) UserName = HttpUtility.UrlDecode(DataTypePlus.requestString(HttpContext.Current.Request.Cookies["UserID"].Value));
            if (HttpContext.Current.Request.Cookies["UserID"] != null) UserID = DataTypePlus.requestInt(HttpContext.Current.Request.Cookies["UserID"].Value);
            if (HttpContext.Current.Request.Cookies["Password"] != null) Password = DataTypePlus.requestString(HttpContext.Current.Request.Cookies["Password"].Value);

            if (UserID > 0 && Password != "")
            {
                if (ChkMd5Password(UserID, Password))
                    return true;
                else
                    return false;
            }
            else
                return false;
        }

        /// <summary>
        /// 判断用户名和密码是否正确
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="Md5password">md5密码</param>
        /// <param name="userType">用户类别</param>
        public static bool ChkMd5Password(string loginForm_name, string Md5password)
        {
            if (GetUserID_by_LoginForm(loginForm_name, Md5password).IsSuccess) return true;
            else return false;
        }
        public static bool ChkMd5Password(int userID_, string Md5password)
        {
            if (GetUserID_by_LoginForm(userID_, Md5password).IsSuccess) return true;
            else return false;
        }
        /// <summary>
        /// 判断用户名和密码是否正确
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="Md5password">md5密码</param>
        /// <param name="userType">用户类别</param>
        public static CallBak<int> GetUserID_by_LoginForm(string loginForm_name, string Md5password)
        {
            CallBak<int> callBak = new CallBak<int>();
            //
            BLL.PAUser bllUser = new BLL.PAUser();
            Model.PAUser modelUser = new Model.PAUser();
            List<Model.PAUser> listModelUser = new List<Model.PAUser>();
            //
            string letter1 = loginForm_name.Substring(0, 1);
            if (loginForm_name != "admin" && (letter1 == "m" || letter1 == "a" || letter1 == "b" || letter1 == "g" || letter1 == "s"))
            {
                int UserID = 0;
                switch (letter1)
                {
                    case "a":
                        BLL.Accountant bll_Accountant = new BLL.Accountant();
                        List<Model.Accountant> listModel_Accountant = bll_Accountant.GetModelList("Number='" + loginForm_name + "'");
                        if (listModel_Accountant.Count > 0) UserID = listModel_Accountant[0].UserID;
                        break;
                    case "b":
                        BLL.Buyer bll_Buyer = new BLL.Buyer();
                        List<Model.Buyer> listModel_Buyer = bll_Buyer.GetModelList("Number='" + loginForm_name + "'");
                        if (listModel_Buyer.Count > 0) UserID = listModel_Buyer[0].UserID;
                        break;
                    case "s":
                        BLL.Store bll_Store = new BLL.Store();
                        List<Model.Store> listModel_Store = bll_Store.GetModelList("Number='" + loginForm_name + "'");
                        if (listModel_Store.Count > 0)
                        {
                            UserID = listModel_Store[0].UserID;
                            if (listModel_Store[0].PAFeeEndDate < DateTime.Now) return callBak.Err("联盟费已到期，请先缴纳后再登录");
                        }
                        break;
                    case "t":
                        BLL.StoreServer bll_StoreServer = new BLL.StoreServer();
                        List<Model.StoreServer> listModel_StoreServer = bll_StoreServer.GetModelList("Number='" + loginForm_name + "'");
                        if (listModel_StoreServer.Count > 0) UserID = listModel_StoreServer[0].UserID;
                        break;
                    case "g":
                        BLL.Supplier bll_Supplier = new BLL.Supplier();
                        List<Model.Supplier> listModel_Supplier = bll_Supplier.GetModelList("Number='" + loginForm_name + "'");
                        if (listModel_Supplier.Count > 0) UserID = listModel_Supplier[0].UserID;
                        break;
                    case "h":
                        BLL.SupplierServer bll_SupplierServer = new BLL.SupplierServer();
                        List<Model.SupplierServer> listModel_SupplierServer = bll_SupplierServer.GetModelList("Number='" + loginForm_name + "'");
                        if (listModel_SupplierServer.Count > 0) UserID = listModel_SupplierServer[0].UserID;
                        break;

                }
                if (UserID == 0) return callBak.Err("输入的编号不存在");
                else listModelUser = bllUser.GetModelList("id=" + UserID + " and password='" + Md5password + "'");
            }
            else listModelUser = bllUser.GetModelList("( username='" + loginForm_name + "' or mobile='" + loginForm_name + "') and password='" + Md5password + "'");

            if (listModelUser != null && listModelUser.Count > 0) modelUser = listModelUser[0];
            else return callBak.Err("用户名或者密码错误");
            if (modelUser.State != (int)EnumHelper.UserState.Nomal) return callBak.Err("账户" + EnumHelper.GetEnumDescription((EnumHelper.UserState)modelUser.State) + "中，无法登陆，请联系管理员");

            callBak.ReturnVal = modelUser.id;
            return callBak;
        }
        public static CallBak<int> GetUserID_by_LoginForm(int userID_, string Md5password)
        {
            CallBak<int> callBak = new CallBak<int>();
            //
            BLL.PAUser bllUser = new BLL.PAUser();
            List<Model.PAUser> listModelUser = bllUser.GetModelList("id=" + userID_ + " and password='" + Md5password + "'");
            if (listModelUser != null && listModelUser.Count > 0)  callBak.ReturnVal =listModelUser[0].id;
            else return callBak.Err("密码错误");
            //
            return callBak;
        }
        /// <summary>
        /// 获取当前登陆用户相关信息
        /// </summary>
        /// <param name="parName">类别</param>
        /// <returns></returns>
        private static string GetCurrentUserInfo(int getType)
        {
            string result = "";
            switch (getType)
            {

                case 2: //密码
                    //result = IO_Session.GetString("Password").ToString(); ;
                    if (HttpContext.Current.Request.Cookies["Password"] != null) result = DataTypePlus.requestString(HttpContext.Current.Request.Cookies["Password"].Value);
                    break;
                case 3: //UserID
                    //result = IO_Session.GetString("Password").ToString(); ;
                    //if (HttpContext.Current.Request.Cookies["UserID"] != null) result = HttpUtility.UrlDecode(DataTypePlus.requestString(HttpContext.Current.Request.Cookies["UserID"].Value));
                    if (HttpContext.Current.Request.Cookies["UserID"] != null) result = DataTypePlus.requestString(HttpContext.Current.Request.Cookies["UserID"].Value);
                    break;


            }

            return result;
        }
        /// <summary>
        /// 获取当前用户密码
        /// </summary>
        /// <returns>密码</returns>
        public static string GetCurrentUserPwd()
        {
            return DataTypePlus.requestString(GetCurrentUserInfo(2));
        }
        /// <summary>
        /// 获取当前用户ID
        /// </summary>
        /// <returns>密码</returns>
        public static int GetCurrentUserID()
        {
            return DataTypePlus.requestInt(GetCurrentUserInfo(3));
        }




        /// <summary>
        /// 获取当前用户
        /// </summary>
        public static Model.PAUser GetCurrentUser()
        {
            BLL.PAUser bllUser = new BLL.PAUser();
            List<Model.PAUser> listModelUser = bllUser.GetModelList("id='" + GetCurrentUserID() + "' and password='" + GetCurrentUserPwd() + "'");
            if (listModelUser != null && listModelUser.Count > 0) return listModelUser[0];
            else { chkIsLogined(); return new Model.PAUser(); }
        }

        /// <summary>
        /// 获取当前用户Type
        /// </summary>
        /// <returns></returns>
        public static EnumHelper.UserType GetCurrentUserType()
        {
            return (EnumHelper.UserType)Enum.ToObject(typeof(EnumHelper.UserType), GetCurrentUser().UserType);
        }



        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static Model.Supplier GetCurrentSupplier()
        {
            BLL.Supplier _bll = new BLL.Supplier();
            List<Model.Supplier> _listModel = _bll.GetModelList("UserID=" + GetCurrentUserID());
            if (_listModel.Count > 0) return _listModel[0];
            else return new Model.Supplier();
        }
        public static int GetCurrentSupplierID() { return GetCurrentSupplier().id; }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static Model.Store GetCurrentStore()
        {
            BLL.Store _bll = new BLL.Store();
            List<Model.Store> _listModel = _bll.GetModelList("UserID=" + GetCurrentUserID());
            if (_listModel.Count > 0) return _listModel[0];
            else return new Model.Store();
        }
        public static int GetCurrentStoreID() { return GetCurrentStore().id; }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static Model.Buyer GetCurrentBuyer()
        {
            BLL.Buyer _bll = new BLL.Buyer();
            List<Model.Buyer> _listModel = _bll.GetModelList("UserID=" + GetCurrentUserID());
            if (_listModel.Count > 0) return _listModel[0];
            else return new Model.Buyer();
        }
        public static int GetCurrentBuyerID() { return GetCurrentBuyer().id; }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static Model.EntryPerson GetCurrentEntryPerson()
        {
            BLL.EntryPerson _bll = new BLL.EntryPerson();
            List<Model.EntryPerson> _listModel = _bll.GetModelList("UserID=" + GetCurrentUserID());
            if (_listModel.Count > 0) return _listModel[0];
            else return new Model.EntryPerson();
        }
        public static int GetCurrentEntryPersonID() { return GetCurrentEntryPerson().id; }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static Model.Receiver GetCurrentReceiver()
        {
            BLL.Receiver _bll = new BLL.Receiver();
            List<Model.Receiver> _listModel = _bll.GetModelList("UserID=" + GetCurrentUserID());
            if (_listModel.Count > 0) return _listModel[0];
            else return new Model.Receiver();
        }
        public static int GetCurrentReceiverID() { return GetCurrentReceiver().id; }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static Model.Accountant GetCurrentAccountant()
        {
            BLL.Accountant _bll = new BLL.Accountant();
            List<Model.Accountant> _listModel = _bll.GetModelList("UserID=" + GetCurrentUserID());
            if (_listModel.Count > 0) return _listModel[0];
            else return new Model.Accountant();
        }
        public static int GetCurrentAccountantID() { return GetCurrentAccountant().id; }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static Model.StoreServer GetCurrentStoreServer()
        {
            BLL.StoreServer _bll = new BLL.StoreServer();
            List<Model.StoreServer> _listModel = _bll.GetModelList("UserID=" + GetCurrentUserID());
            if (_listModel.Count > 0) return _listModel[0];
            else return new Model.StoreServer();
        }
        public static int GetCurrentStoreServerID() { return GetCurrentStoreServer().id; }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static Model.SupplierServer GetCurrentSupplierServer()
        {
            BLL.SupplierServer _bll = new BLL.SupplierServer();
            List<Model.SupplierServer> _listModel = _bll.GetModelList("UserID=" + GetCurrentUserID());
            if (_listModel.Count > 0) return _listModel[0];
            else return new Model.SupplierServer();
        }
        public static int GetCurrentSupplierServerID() { return GetCurrentSupplierServer().id; }

        /// <summary>
        /// 获取编号
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentNumber()
        {
            Model.PAUser modelPAUser = GetCurrentUser();
            switch ((EnumHelper.UserType)modelPAUser.UserType)
            {
                case EnumHelper.UserType.Administrator:
                    return "";
                case EnumHelper.UserType.StoreServer:
                    return GetCurrentStoreServer().Number;
                case EnumHelper.UserType.SupplierServer:
                    return GetCurrentSupplierServer().Number;
                case EnumHelper.UserType.Accountant:
                    return GetCurrentAccountant().Number;
                case EnumHelper.UserType.Buyer:
                    return GetCurrentBuyer().Number;
                case EnumHelper.UserType.Receiver:
                    return GetCurrentReceiver().Number;
                case EnumHelper.UserType.Supplier:
                    return GetCurrentSupplier().Number;
                case EnumHelper.UserType.Store:
                    return GetCurrentStore().Number;
                case EnumHelper.UserType.EntryPerson:
                    return GetCurrentEntryPerson().Number;
                default: return "";
            }
        }
        /// <summary>
        /// 获取名称
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentName()
        {
            Model.PAUser modelPAUser = GetCurrentUser();
            switch ((EnumHelper.UserType)modelPAUser.UserType)
            {
                case EnumHelper.UserType.Administrator:
                    return "管理员";
                case EnumHelper.UserType.StoreServer:
                    return modelPAUser.Username;
                case EnumHelper.UserType.SupplierServer:
                    return modelPAUser.Username;
                case EnumHelper.UserType.Accountant:
                    return modelPAUser.Username;
                case EnumHelper.UserType.Buyer:
                    return modelPAUser.Username;
                case EnumHelper.UserType.Receiver:
                    return modelPAUser.Username;
                case EnumHelper.UserType.Supplier:
                    return GetCurrentSupplier().Name;
                case EnumHelper.UserType.Store:
                    return GetCurrentStore().Name;
                case EnumHelper.UserType.EntryPerson:
                    return modelPAUser.Username;
                default: return "";
            }
        }


        /// <summary>
        /// 当前用户是否属于用户组list
        /// </summary>
        /// <param name="listUserType_"></param>
        /// <returns></returns>
        public static bool InUserType(List<EnumHelper.UserType> listUserType_)
        {
            EnumHelper.UserType meUserType = GetCurrentUserType();
            foreach (EnumHelper.UserType usertype in listUserType_)
            {
                if (usertype == meUserType) return true;
            }
            return false;
        }



        /// <summary>
        /// 判断是否已经登陆
        /// </summary>
        public static void chkIsLogined()
        {
            if (!IsLogined())
            {
                Logout();
                JsHelper.Alert("请先登录再操作");
                JsHelper.RefreshParent();
            }
        }


    }


}